package controlador;

import helpers.IModelSerializer;
import helpers.IModelValidator;
import java.util.List;


import persistencia.IDAOTEMPLATE;
import modelo.AbstractModel;


public class CRUDController extends AbstractController
{
		

	public CRUDController()
	{
		
	}

	
	public void Create(String XML) throws Exception
	{
		IDAOTEMPLATE dao = instancesPool.getDao();
		IModelSerializer modelSerializer = instancesPool.getmSerializer();
		IModelValidator modelValidator = instancesPool.getmValidator();
		
		AbstractModel Model = modelSerializer.getFirstObjectFromXML(XML);
		
		if (modelValidator.isValidModel(Model))
		{
			dao.createModel(Model);
		}
		else
		{
			String ValidationMessage = modelValidator.getNotValidModelMessage(Model);
			throw new Exception("Model isn't valid. Reason :"+ ValidationMessage);
		}
		
	}

	public String Read(String model, int Page) throws Exception
	{
		IDAOTEMPLATE dao = instancesPool.getDao();
		IModelSerializer modelSerializer = instancesPool.getmSerializer();
		
		try
		{
			List<AbstractModel> LModelos = dao.listModelByType(model,Page);
			
			
			String XMLReturn = modelSerializer.getXMLFromObjectList(LModelos,10);		
		
			return XMLReturn;
		}
		catch(Exception e)
		{
			throw e;	
		}
	}
	
	public void Update(String XML) throws Exception
	{
		IDAOTEMPLATE dao = instancesPool.getDao();
		IModelSerializer modelSerializer = instancesPool.getmSerializer();
		IModelValidator modelValidator = instancesPool.getmValidator();
		
		AbstractModel Model = modelSerializer.getFirstObjectFromXML(XML);
		
		if (modelValidator.isValidModel(Model))
		{
		dao.updateModel(Model);
		}
		else 
		{
			String ValidationMessage = modelValidator.getNotValidModelMessage(Model);
			throw new Exception("Model isn't valid. Reason :"+ ValidationMessage);
		}
		
	}

	public void Delete(String XML) throws Exception
	{
		IDAOTEMPLATE dao = instancesPool.getDao();
		IModelSerializer modelSerializer = instancesPool.getmSerializer();
		
		AbstractModel Model = modelSerializer.getFirstObjectFromXML(XML);
		
		try
		{
			dao.deleteModel(Model.getId(), Model.getClass());
		}
		catch (Exception e)
		{
			throw e;			
		}
		
	}


}
